package com.example.venue_reservation_service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.venue_reservation_service.converter.ListConverter;
import com.example.venue_reservation_service.domain.Comment;
import com.example.venue_reservation_service.domain.User;
import com.example.venue_reservation_service.domain.UserLike;
import com.example.venue_reservation_service.dto.DelDTO;
import com.example.venue_reservation_service.dto.PageDTO;
import com.example.venue_reservation_service.dto.SearchDTO;
import com.example.venue_reservation_service.exception.SensitiveFilterException;
import com.example.venue_reservation_service.filter.SensitiveFilter;
import com.example.venue_reservation_service.mapper.CommentMapper;
import com.example.venue_reservation_service.mapper.UserMapper;
import com.example.venue_reservation_service.service.CommentService;
import com.example.venue_reservation_service.service.UserLikeService;
import com.example.venue_reservation_service.utils.RedisUtil;
import com.example.venue_reservation_service.vo.AvatarVO;
import com.example.venue_reservation_service.vo.QueryVO;
import com.example.venue_reservation_service.vo.Result;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
* @author 31586
* @description 针对表【venue_comment(用户评论主表)】的数据库操作Service实现
* @createDate 2025-06-03 15:00:23
*/
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
    implements CommentService{

    @Resource
    private RedisUtil redisUtil;

    private final static String REDIS_KEY = "sensitive-word";

    @Resource
    private UserLikeService userLikeService;

    @Resource
    private UserMapper userMapper;

    @Value("${access.url}")
    private String accessUrl;

    @Override
    public Result queryComment(PageDTO dto) {
        Page<Comment> page = new Page(dto.getCurrent(), dto.getSize());
        page = page(page, null);
        QueryVO<Comment> vo = new QueryVO<>();
        vo.setTotal(page.getTotal());
        vo.setList(page.getRecords());
        return Result.ok(vo).message("数据加载完成");
    }

    @Override
    public Result queryByUser(SearchDTO dto) {
        Page<Comment> page = new Page<>(dto.getCurrent(), dto.getSize());
        LambdaQueryWrapper<Comment> wrapper = Wrappers.lambdaQuery();
        if (dto.getOnlyOne() == 1) {
            wrapper.eq(Comment::getUserId, dto.getUserId());
        }
        wrapper.eq(Comment::getStatus, 2)
                .orderByDesc(Comment::getUpdateTime)
                .orderByDesc(Comment::getCreateTime);

        page = page(page, wrapper);
        QueryVO<AvatarVO> vo = new QueryVO<>();
        vo.setTotal(page.getTotal());
        List<AvatarVO> list = new ArrayList<>();
        page.getRecords().forEach(item -> {
            User user = userMapper.selectById(item.getUserId());
            if(user.getIsUpload() == 1){
                user.setAvatar(accessUrl + user.getAvatar());
            }
            AvatarVO ele = BeanUtil.copyProperties(user, AvatarVO.class);
            UserLike like = userLikeService.getOne(Wrappers.<UserLike>lambdaQuery()
                    .eq(UserLike::getUserId, dto.getUserId())
                    .eq(UserLike::getCommentId, item.getId()));
            if (Optional.ofNullable(like).isEmpty() || like.getIsDelete() == 1) {
                ele.setIsLike(0);
            }else{
                ele.setIsLike(1);
            }
            BeanUtil.copyProperties(item, ele);
            list.add(ele);
        });
        vo.setList(list);
        return Result.ok(vo).message("数据加载完成");
    }

    @Override
    public Result createComment(Comment comment) {
        if (Optional.ofNullable(comment.getUserId()).isEmpty() || Optional.ofNullable(userMapper.selectById(comment.getUserId())).isEmpty()){
            return Result.fail().message("用户信息不存在");
        }
        List<String> list;
        try {
            list = ListConverter.stringToList((String) redisUtil.get(REDIS_KEY));
        } catch (Exception e) {
            // 转换为自定义异常并添加错误码
            throw new SensitiveFilterException("SENSITIVE_001", "敏感词库加载失败");
        }
        SensitiveFilter filter = new SensitiveFilter();
        filter.buildTrie(list);
        String content = filter.filter(comment.getContent());
        comment.setContent(content);
        comment.setStatus(2); // 过滤完成后默认为发布状态
        comment.setCreateTime(LocalDateTime.now());
        comment.setUpdateTime(LocalDateTime.now());
        save(comment);
        return Result.ok().message("评论发布成功");
    }

    @Override
    public Result withdrawComment(Integer id) {
        Comment comment = getById(id);
        if (Optional.ofNullable(comment).isEmpty()) {
            return Result.fail().message("未查询到评论信息");
        }
        comment.setStatus(comment.getStatus() == 1 ? 2 : 1);
        updateById(comment);
        return Result.ok().message(comment.getStatus() == 1 ? "撤回成功" : "恢复成功");
    }

    @Override
    public Result like(Integer userId, Integer commentId) {
        UserLike like = userLikeService.getOne(Wrappers.<UserLike>lambdaQuery()
                .eq(UserLike::getUserId, userId)
                .eq(UserLike::getCommentId, commentId));
        if (Optional.ofNullable(like).isEmpty()) {
            // 用户之前未点赞过该条评论
            like = new UserLike();
            like.setCommentId(commentId);
            like.setUserId(userId);
            like.setCreateTime(LocalDateTime.now());
            like.setIsDelete(0);
            userLikeService.save(like);
        }else{
            like.setIsDelete(like.getIsDelete() == 1 ? 0 : 1);
            userLikeService.updateById(like);
        }
        return Result.ok().message(like.getIsDelete() == 1 ? "取消点赞" : "点赞成功");
    }

    @Override
    public Result singleRemove(Integer userId, Integer commentId) {
        Comment comment = getById(commentId);
        if(Objects.equals(comment.getUserId(), userId)){
            removeById(commentId);
        }
        return Result.ok().message("删除成功");
    }

    @Override
    public Result batchRemove(DelDTO dto) {
        for (Integer commentId : dto.getList()) {
            Comment comment = getById(commentId);
            if(Objects.equals(comment.getUserId(), dto.getUserId())){
                removeById(commentId);
            }
        }
        return Result.ok().message("清理成功");
    }


}




